﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team (cellcloudproject@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellTalkCommand.h"
#include "CellTalkPacketDefinition.h"
#include "CellNucleus.h"
#include "CellMessage.h"
#include "CellPacket.h"
#include "CellSession.h"
#include "CellTalkService.h"
#include "CellCellet.h"
#include "CellSerializable.h"
#include "CellPrimitive.h"
#include "CellLoggerManager.h"
#include "CellStringConverter.h"

namespace cell
{

//-----------------------------------------------------------------------
const char TalkCommand::SC_SUCCESSFUL[5]      = {'0', '0', '0', '0', '\0'};
const char TalkCommand::SC_FAILED[5]          = {'0', '0', '0', '1', '\0'};
const char TalkCommand::SC_FAILED_NOCELLET[5] = {'0', '0', '1', '0', '\0'};

//-----------------------------------------------------------------------
TalkCommand::TalkCommand(void)
	: mService(NULL)
{
}
//-----------------------------------------------------------------------
TalkCommand::TalkCommand(TalkService* service)
	: mService(service)
{
}
//-----------------------------------------------------------------------
TalkCommand::~TalkCommand(void)
{
}

//-----------------------------------------------------------------------
TalkCheckCommand::TalkCheckCommand(TalkService* service, Session* session, Packet* packet)
	: TalkCommand(service)
	, mSession(session)
	, mPacket(packet)
{
	memset(mTag, 0x0, sizeof(mTag));
	TPT_CHECK_ASSIGN(mTag);
}
//-----------------------------------------------------------------------
TalkCheckCommand::~TalkCheckCommand(void)
{
}
//-----------------------------------------------------------------------
void TalkCheckCommand::execute(void)
{
	// 包格式：原文

	char plaintext[32] = {0x0};
	mPacket->getSubsegment(plaintext, 0);

	bool checkin = false;
	TalkService::Certificate* cert = mService->getCertificate(mSession);
	if (NULL != cert)
	{
		if (cert->plaintext == plaintext)
		{
			checkin = true;
		}
	}

	String msg = "Session ";
	msg += mSession->getAddress().getHostAddress();
	msg += "/";
	msg += StringConverter::toString(mSession->getAddress().getPort());

	// 是否校验通过
	if (checkin)
	{
		msg += " checkin.";
		LoggerManager::getSingleton().log(msg);

		// 同意 Session，使其合法
		mService->acceptSession(mSession);

		// 包格式：成功码|内核标签

		Packet packet(mTag, 2);
		packet.appendSubsegment(SC_SUCCESSFUL, 4);
		String tag = Nucleus::getSingleton().getTagAsString();
		packet.appendSubsegment(tag.c_str(), tag.length());
		// 发送数据包
		char* data = CELL_ALLOC_T(char, packet.getTotalLength() + 1, MEMCATEGORY_GENERAL);
		memset(data, 0x0, packet.getTotalLength() + 1);
		int len = Packet::pack(data, &packet);
		Message message(data, len);
		mSession->write(&message);
		CELL_FREE(data, MEMCATEGORY_GENERAL);
	}
	else
	{
		msg += " checkout.";
		LoggerManager::getSingleton().log(msg);

		// 拒绝 Session
		mService->rejectSession(mSession);
	}
}

//-----------------------------------------------------------------------
TalkRequestCelletCommand::TalkRequestCelletCommand(TalkService* service, Session* session, Packet* packet)
	: TalkCommand(service)
	, mSession(session)
	, mPacket(packet)
{
	memset(mTag, 0x0, sizeof(mTag));
	TPT_REQUEST_ASSIGN(mTag);
}
//-----------------------------------------------------------------------
TalkRequestCelletCommand::~TalkRequestCelletCommand(void)
{
}
//-----------------------------------------------------------------------
void TalkRequestCelletCommand::execute(void)
{
	// 包格式：Cellet标识串|请求方标签

	// 获取请求的 Cellet 标识
	char identifier[128] = {0x0};
	mPacket->getSubsegment(identifier, 0);

	// 获取请求方的 TAG
	char talkTag[64] = {0x0};
	mPacket->getSubsegment(talkTag, 1);

	if (false == mService->isProxyMode())
	{
		// 非代理模式
		// 包格式：请求方标签|成功码|Cellet识别串|Cellet版本

		Packet packet(mTag, 1);
		packet.appendSubsegment(talkTag, strlen(talkTag));

		// 请求 Cellet 服务
		TalkTracker* tracker = mService->requestCellet(mSession, talkTag, identifier);

		if (NULL != tracker && NULL != tracker->activeCellet)
		{
			// 查找到正确的 Cellet 返回 Cellet 信息。
			// 返回请求成功
			packet.appendSubsegment(SC_SUCCESSFUL, 4);

			// 数据写入
			// identifier
			String id = tracker->activeCellet->getFeature().getIdentifier();
			packet.appendSubsegment(id.c_str(), id.length());
			// version
			String version = tracker->activeCellet->getFeature().getVersion().toString();
			packet.appendSubsegment(version.c_str(), version.length());
		}
		else
		{
			// 数据写入
			packet.appendSubsegment(TalkCommand::SC_FAILED_NOCELLET, 4);
		}

		// 数据打包
		char* data = CELL_ALLOC_T(char, packet.getTotalLength() + 1, MEMCATEGORY_GENERAL);
		memset(data, 0x0, packet.getTotalLength() + 1);
		uint32 len = Packet::pack(data, &packet);
		// 发送
		Message message(data, len);
		mSession->write(&message);
		CELL_FREE(data, MEMCATEGORY_GENERAL);
	}
	else
	{
		// 代理模式

		mService->getProxy()->requestCellet(mSession, talkTag, identifier);
	}
}

//-----------------------------------------------------------------------
TalkDialogueCelletCommand::TalkDialogueCelletCommand(TalkService* service, Session* session, Packet* packet)
	: TalkCommand(service)
	, mSession(session)
	, mPacket(packet)
{
	memset(mTag, 0x0, sizeof(mTag));
	TPT_DIALOGUE_ASSIGN(mTag);
}
//-----------------------------------------------------------------------
TalkDialogueCelletCommand::~TalkDialogueCelletCommand(void)
{
}
//-----------------------------------------------------------------------
void TalkDialogueCelletCommand::execute(void)
{
	// 包格式：序列化的原语|源标签

	if (mPacket->getSubsegmentNum() < 2)
	{
		char log[64] = {0x0};
		sprintf(log, "[CC] Dialogue packet format error");
		LoggerManager::getSingleton().log(log);
		return;
	}

	uint sublen = mPacket->getSubsegmentLength(0);
	char* pridata = CELL_ALLOC_T(char, sublen + 1, MEMCATEGORY_GENERAL);
	memset(pridata, 0x0, sublen + 1);
	mPacket->getSubsegment(pridata, 0);

	char talkerTag[64] = {0x0};
	mPacket->getSubsegment(talkerTag, 1);

	uint16 sn = 0;
	mPacket->getSequenceNumber(&sn);

	SerializerStream stream;
	stream << pridata;

	// 反序列化原语
	Primitive primitive(talkerTag);
	primitive.read(stream);

	// 与 Cellet 进行对话
	if (false == mService->isProxyMode())
	{
		mService->dialogueCellet(mSession, talkerTag, primitive);
	}
	else
	{
		mService->getProxy()->dialogueCellet(mSession, talkerTag, primitive);
	}

	CELL_FREE(pridata, MEMCATEGORY_GENERAL);
}


//---------------------------------------------------------------------------
TalkProxyCommand::TalkProxyCommand(TalkService* service, Session* session, Packet* packet)
	: TalkCommand(service)
	, mSession(session)
	, mPacket(packet)
{
}
//---------------------------------------------------------------------------
TalkProxyCommand::~TalkProxyCommand(void)
{
}
//---------------------------------------------------------------------------
void TalkProxyCommand::execute(void)
{
	// 包格式：请求端标签

	char tag[64] = {0x0};
	mPacket->getSubsegment(tag, 0);
	// Session 如果已经获得过 Cellet 服务，则不能再改变代理模式
	if (NULL != mService->getSession(tag))
	{
		return;
	}

	// 设置为代理模式
	bool ret = mService->configProxy(mSession);

	// 包格式：状态码|内核标签

	Packet packet(mTag, 1);
	if (ret)
		packet.appendSubsegment(SC_SUCCESSFUL, 4);
	else
		packet.appendSubsegment(SC_FAILED, 4);

	String nucleusTag = Nucleus::getSingleton().getTagAsString();
	packet.appendSubsegment(nucleusTag.c_str(), nucleusTag.length());

	// 数据打包
	char* data = CELL_ALLOC_T(char, packet.getTotalLength() + 1, MEMCATEGORY_GENERAL);
	memset(data, 0x0, packet.getTotalLength() + 1);
	uint len = Packet::pack(data, &packet);
	// 发送
	Message message(data, len);
	mSession->write(&message);
	CELL_FREE(data, MEMCATEGORY_GENERAL);
}


//-----------------------------------------------------------------------
TalkHeartbeatCommand::TalkHeartbeatCommand(TalkService* service, Session* session, Packet* packet)
	: TalkCommand(service)
	, mSession(session)
{
}
//-----------------------------------------------------------------------
TalkHeartbeatCommand::~TalkHeartbeatCommand(void)
{
}
//-----------------------------------------------------------------------
void TalkHeartbeatCommand::execute(void)
{
	mService->updateSessionTickTime(mSession);
}

} // end namespace cell
